import { fetch } from "@tauri-apps/plugin-http";
import { logout } from "./utils";

export type RequestOption = {
    url: string,
    headers?: { [key: string]: any },
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE',
    dataType?: 'application/json' | 'formData'
    contentType?: 'application/json'
    data?: { [key: string]: any },
};

export const request = async (request: RequestOption): Promise<any> => {
    if (request.method === 'POST') {
        return await post(request);
    } else {
        return await get(request);
    }
};


export const get = async (request: RequestOption): Promise<any> => {

    let response = await fetch(request.url, {
        headers: {
            ...request.headers
        },
        method: 'GET',
        body: null
    });

    console.log(response);
    if (response && response.status === 401) {
        //
        logout();
        window.location.reload()
        return null;
    }
    return response;
};

export const post = async (request: RequestOption): Promise<any> => {

    let response = null;

    if (request.dataType === 'application/json') {
        response = await fetch(request.url, {
            headers: {
                'Content-Type': 'application/json',
                ...request.headers
            },
            method: 'POST',
            body: JSON.stringify(request.data != null ? request.data : {})
        });
    } else {
        response = await fetch(request.url, {
            headers: {
                ...request.headers
            },
            method: 'POST',
            // body: http.Body.form(request.data != null ? request.data : {})
        });
    }
    console.log(response);
    if (response && response.status === 401) {
        //
        logout();
        window.location.reload()
        return null;
    }
    return response;

};

export default {
    get,
    post
};